package com.zcs.thread.communication;

/**
 * 等待/通知机制
 *
 * @author zcs
 * @since 2023/4/21
 */
public class WaitAndNotify {

    private static final byte[] LOCK = new byte[0];

    /**
     * 需要注意的是等待/通知机制使用的是使用同一个对象锁，如果你两个线程使用的是不同的对象锁，那它们之间是不能用等待/通知机制通信的。
     * @param args
     * @throws InterruptedException
     */

    public static void main(String[] args) throws InterruptedException {
        new ThreadA().aVoid();
        Thread.sleep(10);
        new ThreadB().bVoid();
    }


    static class ThreadA {

        public void aVoid() {
            new Thread(() -> {
                synchronized (LOCK) {
                    for (int i = 0; i < 5; i++) {
                        try {
                            System.out.println("ThreadA: " + i);
                            LOCK.notify();
                            LOCK.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    LOCK.notify();
                }
            }).start();
        }
    }

    static class ThreadB {
        public void bVoid() {
            new Thread(() -> {
                synchronized (LOCK) {
                    for (int i = 0; i < 5; i++) {
                        try {
                            System.out.println("ThreadB: " + i);
                            LOCK.notify();
                            LOCK.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    LOCK.notify();
                }
            }).start();
        }
    }

}
